//
//  AddAcountViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/28.
//  Copyright © 2017年 bob. All rights reserved.
//确认订单控制器。

#import "AddAcountViewController.h"
#import "LoginStatuesModel.h"
#import "RegisterShopModel.h"
#import "RSTableHeadView.h"
#import "RegisterSingleTableViewCell.h"
#import "RegisterPopTableViewCell.h"
#import "RegisterMorePicTableViewCell.h"
#import "RegisterMoreTextTableViewCell.h"
#import "RegisterSpicTableViewCell.h"
#import "ChooseView.h"
#import "DatePickView.h"
#import "ScanCodeTableViewCell.h"
#import "ScanPhotoViewController.h"
#import "AddSAcountModel.h"
#import "AcountListTableViewCell.h"
#import "AcountBtnTableViewCell.h"
#import "AcountGoodsViewController.h"
#import "CandLViewController.h"
#import "OutAccountViewController.h"
@interface AddAcountViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@property(nonatomic,strong)TB_TableView *RegisterTableView;

@property(nonatomic,strong)RegisterShopModel *ShopModel;

@property(nonatomic,strong)AddSAcountModel *AddModel;

@property(nonatomic,strong)NSMutableArray*AcountListArr;//台账列表

@property(nonatomic,strong)NSMutableArray *postListArr;//台账发送列表,//装字典，怕参数变化，模型解析不出来新参数

@property(nonatomic,copy)NSString*headimage;

@property(nonatomic,strong)UIButton *ProvideBtn;

@property(nonatomic,assign)BOOL editAcount;//是否编辑台账

@property(nonatomic,assign)NSInteger editRecoredRow;//记录编辑点击的行

@end

@implementation AddAcountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHidenKeyToolBar=NO;
    
    self.editAcount=NO;
    
    self.isScanphotos=YES;//有预览图片功能
    
    [self.view addSubview:self.RegisterTableView];
    
    [self loadDates];
    
    // Do any additional setup after loading the view.
}

-(NSMutableArray*)AcountListArr
{
    if (!_AcountListArr) {
        
        _AcountListArr=[NSMutableArray array];
    }
    return _AcountListArr;
}

-(NSMutableArray*)postListArr
{
    if (!_postListArr) {
        
        _postListArr=[NSMutableArray array];
    }
    
    return _postListArr;
}


-(UIButton*)ProvideBtn
{
    if (!_ProvideBtn) {
        
        _ProvideBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        
          if (kDevice_Is_iPhoneX) {
        
                   _ProvideBtn.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64-IPhoneXTableHeight, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
              
          }else{
        _ProvideBtn.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
          }
        [_ProvideBtn setTitle:self.BtnStr forState:UIControlStateNormal];
        
        _ProvideBtn.titleLabel.font=[UIFont systemFontOfSize:21];
        
        [_ProvideBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_ProvideBtn addTarget:self action:@selector(GotoOption:) forControlEvents:UIControlEventTouchUpInside];
        
        [_ProvideBtn setBackgroundColor:TBColorProvideBtnbg];
 
    }
    
    return _ProvideBtn;
}

-(void)viewDidDisappear:(BOOL)animated
{
    self.isHidenKeyToolBar=YES;
    
}


-(void)loadDates
{
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:self.requrl andrequestTime:5 andParams: self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    
    
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        NSLog(@"%@",responseObject);
        [self stopLoadingAnimation];
     
        self.ShopModel=[RegisterShopModel mj_objectWithKeyValues:responseObject];
     
        if (responseStatus==1) {
            
            NSArray*Acountarr=responseObject[@"data"];
            
            if (Acountarr.count>2) {
                
                 self.AddModel=[AddSAcountModel mj_objectWithKeyValues:Acountarr[2]];
                
                [self.AcountListArr addObjectsFromArray:self.AddModel.list];
                
                //保存字典：原因怕参数变化，模型解析不出来新参数
                NSDictionary *Titledic=Acountarr[2];
                
                for (NSDictionary *dic in Titledic[@"list"]) {
                    
                    [self.postListArr addObject:dic];
                    
                }
                
            }
            
            //请求成功
            if (self.ShopModel.data.count==0) {
                
                self.Type=TBNODateType;
                
            }else{
                
                [self.RegisterTableView reloadData];
                
                if(self.isOrder)
                {
                    [self.view addSubview:self.Footview];
                }else{
                    [self.view addSubview:self.ProvideBtn];
                }
            }
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
        
    }];
    
}

-(TB_TableView*)RegisterTableView
{
    if (!_RegisterTableView) {
        
        CGRect frame;
        
        if (kDevice_Is_iPhoneX) {
            
            frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-44*SCREEN_WIDTH/320-IPhoneXTableHeight);
            
        }else{
            
            frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-44*SCREEN_WIDTH/320);
        }
        
        _RegisterTableView=[[TB_TableView alloc]initWithFrame:frame];
        _RegisterTableView.delegate=self;
        _RegisterTableView.dataSource=self;
        
        _RegisterTableView.estimatedRowHeight=44;
        
        _RegisterTableView.tableFooterView=[[UIView alloc]init];
        
        [_RegisterTableView registerNib:[UINib nibWithNibName:@"RegisterSingleTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell1"];
        
        [_RegisterTableView registerNib:[UINib nibWithNibName:@"RegisterPopTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell2"];
        
        [_RegisterTableView registerClass:[RegisterMorePicTableViewCell class] forCellReuseIdentifier:@"TypeCell3"];
        
        [_RegisterTableView registerNib:[UINib nibWithNibName:@"RegisterMoreTextTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell4"];
        
        [_RegisterTableView registerNib:[UINib nibWithNibName:@"RegisterSpicTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell5"];
        
        [_RegisterTableView registerNib:[UINib nibWithNibName:@"ScanCodeTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell6"];
        
         [_RegisterTableView registerNib:[UINib nibWithNibName:@"AcountListTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell7"];
        
           [_RegisterTableView registerNib:[UINib nibWithNibName:@"AcountBtnTableViewCell" bundle:nil] forCellReuseIdentifier:@"TypeCell8"];
        
       
      
        [_RegisterTableView registerClass:[RSTableHeadView class] forHeaderFooterViewReuseIdentifier:@"head"];
        
        [self configureNeedShowEmptyDataSetScrollView:_RegisterTableView];
        
    }
    
    return _RegisterTableView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.ShopModel.data.count)
    {
        return 1;
    }
    return 0;
    
//    return self.ShopModel.data.count;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section<2) {
        
        RSData *Datamodel=self.ShopModel.data[section];
        
        return Datamodel.list.count;
        
    }else{
        
        return self.AcountListArr.count;
        
    }
    
  
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section<self.ShopModel.data.count-1) {
        
        RSData *Datamodel=self.ShopModel.data[indexPath.section];
        
        RSList *list=Datamodel.list[indexPath.row];
        
        if (list.fieldType==1||list.fieldType==2) {
            
            RegisterSingleTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell1" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleName=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleName=list.name;
            }
            
            if (list.fieldType==2) {
                
                cell.RtextFile.secureTextEntry=YES;
                
            }else{
                
                cell.RtextFile.secureTextEntry=NO;
                
            }
            
            cell.VaildType=list.vaildType;
            
            cell.RtextFile.text=list.value;
            
            [cell.RtextFile removeAllBlocksForControlEvents:UIControlEventEditingChanged];
            
            [cell.RtextFile addBlockForControlEvents:UIControlEventEditingChanged block:^(id  _Nonnull sender) {
                
                UITextField *textf=sender;
                
                list.value=textf.text;
                
            }];
            
            return cell;
            
        }else if (list.fieldType==3||list.fieldType==7||list.fieldType==9 || list.fieldType==14)
        {
            
            RegisterPopTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell2" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleName=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleName=list.name;
            }
            
            if (list.fieldType==14) {
                
                NSString *Content=@"";
                
                if(self.isOrder)
                {
                    for (RSItems *item in list.items) {
                        
                        if (item.value.integerValue == self.supplierId) {
                            
                            Content=item.name;
                            
                            break;
                        }
                        
                    }
                }else{
                    for (RSItems *item in list.items) {
                        
                        if ([item.value isEqualToString:list.value]) {
                            
                            Content=item.name;
                            
                            break;
                        }
                        
                    }
                }
            
                cell.RContentLabel.text=Content;
                
            }else{
                
                cell.RContentLabel.text=list.value;
                
            }
            
            
            return cell;
            
        }else if (list.fieldType==5||list.fieldType==12)
        {
            RegisterMorePicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell3" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleName=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleName=list.name;
            }
            
            cell.isEdit=YES;//是否可编辑
            
            cell.ImageArr=[HelpWay imageStrToArr:list.value];//传递图片数组
            
            TBWeak;
            //删除图片
            cell.delePhoto=^(NSInteger num)
            {
                NSArray *arr=[HelpWay imageStrToArr:list.value];
                
                NSMutableArray *ReArr=[[NSMutableArray alloc]initWithArray:arr];
                
                [ReArr removeObjectAtIndex:num];
                
                NSString*FinalStr=@"";
                
                for (NSString*imageStr in ReArr) {
                    
                    if (FinalStr.length==0) {
                        
                        FinalStr=imageStr;
                    }else{
                        
                        
                        FinalStr=[NSString stringWithFormat:@"%@|%@",FinalStr,imageStr];
                    }
                    
                }
                
                list.value=FinalStr;
                
                [weakSelf.RegisterTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                
            };
            
            //浏览图片
            cell.ScanBlock=^(NSInteger num)
            {
                [weakSelf.ScanPhotoArr removeAllObjects];
                
                for (NSString*imagestr in [HelpWay imageStrToArr:list.value]) {
                    
                    [weakSelf.ScanPhotoArr addObject:[MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",ReqUrl,imagestr]]]];
                    
                }
                
                [weakSelf GoToPhotoScanAndIndex:num];
                
            };
            
            //上传图片
            cell.UploadBlock=^()
            {
                BOOL isScan=NO;
                
                if ([self.postUrl isEqualToString:@"/index.php/FoodCheckApi/ledgerInSimpleAdd.json"]) {
                    
                    isScan=YES;
                }
                
                [weakSelf GotoLibaraySelectPhotoNum:9 andIsCantainScan:isScan andBlock:^(NSString * armStr) {
                    
                    if (list.value.length==0) {
                        
                        list.value=armStr;
                        
                    }else{
                        
                        list.value=[NSString stringWithFormat:@"%@|%@",list.value,armStr];
                    }
                    
                    [weakSelf.RegisterTableView reloadData];
                    
                }];
                
            };
            
            return cell;
            
        }else if (list.fieldType==4){
            
            RegisterSpicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell5" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleName=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleName=list.name;
            }
            
            if (list.value.length==0) {
                
                cell.IcoImageView.userInteractionEnabled=NO;
                
            }else{
                
                cell.IcoImageView.userInteractionEnabled=YES;
                
                self.headimage=list.value;
                
                UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ShowHEAD)];
                
                [cell.IcoImageView addGestureRecognizer:tap];
                
            }
            
            [cell.IcoImageView LoadWebImageWithName:list.value andIsOrgin:NO];
            
            return cell;
            
        }else if (list.fieldType==8){
            
            ScanCodeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell6" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleLabel.text=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleLabel.text=list.name;
            }
            
            cell.CodeTextFile.text=list.value;
            
            [cell.CodeTextFile removeAllBlocksForControlEvents:UIControlEventEditingChanged];
            
            [cell.CodeTextFile addBlockForControlEvents:UIControlEventEditingChanged block:^(id  _Nonnull sender) {
                
                UITextField *textf=sender;
                
                list.value=textf.text;
                
            }];
            
            [cell.ScanBtn bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
            
            [cell.ScanBtn bk_addEventHandler:^(id sender) {
                //去扫描
                
                ScanPhotoViewController*scanVC=[ScanPhotoViewController new];
                
                scanVC.Scantype=2;
                
                scanVC.resultBlock=^(NSString *Str)
                {
                    
                    list.value=Str;
                    
                    [self.RegisterTableView reloadData];
                };
                
                [self.navigationController pushViewController:scanVC animated:YES];
                
            } forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
            
        }else if (list.fieldType==10)
        {
         
            AcountBtnTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell8" forIndexPath:indexPath];
            
            
            cell.block=^()
            {
                //添加操作
                [self addLocaCount];
            };
            
            return cell;
            
        }else if (list.fieldType==11)
        {
         
            UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"hidencell"];
            
            if (!cell) {
                
                cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"hidencell"];
            }
            
            return cell;
            
        }else{
            
            RegisterMoreTextTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell4" forIndexPath:indexPath];
            
            if (list.isVaild) {
                
                cell.TitleName=[NSString stringWithFormat:@"%@*",list.name];
                
            }else{
                
                cell.TitleName=list.name;
            }
            
            cell.RTextView.text=list.value;
            
            cell.VaildType=list.vaildType;
            
            cell.RTextView.delegate=self;
            
            cell.RTextView.tag=indexPath.row+indexPath.section*1000+8000;
            
            return cell;
        }
        
    }else{
        
        SAcountList *listmodel=self.AcountListArr[indexPath.row];

        AcountListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TypeCell7" forIndexPath:indexPath];
        
        cell.model=listmodel;
        
        cell.Dblock=^(UITableViewCell*dcell)
        {
            [UIAlertView bk_showAlertViewWithTitle:@"是否删除这条商品?" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self.postListArr removeObjectAtIndex:self.editRecoredRow];
                    
                    [self.AcountListArr removeObjectAtIndex:self.editRecoredRow];
                    
                    [self.RegisterTableView reloadData];
                }
                
            }];
      
        };
        
        return cell;
        
    }
    
   
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section>=self.ShopModel.data.count-1) {
        
        return UITableViewAutomaticDimension;
        
    }
    
    RSData *Datamodel=self.ShopModel.data[indexPath.section];
    
    RSList *list=Datamodel.list[indexPath.row];
    
    if (list.fieldType==1||list.fieldType==2||list.fieldType==3||list.fieldType==7||list.fieldType==9||list.fieldType==14) {
        
        return UITableViewAutomaticDimension;
        
    }else if (list.fieldType==6)
    {
        
        return 100;
        
    }else if (list.fieldType==4){
        
        
        return 60;
        
    } else if (list.fieldType==5||list.fieldType==12){
        
        RSData *Datamodel=self.ShopModel.data[indexPath.section];
        
        RSList *list=Datamodel.list[indexPath.row];
        
        NSArray *arr=[HelpWay imageStrToArr:list.value];
        
        NSInteger colorm=arr.count/3+1;//每行放三个，一个有多少行
        
        CGFloat cellHeight=(SCREEN_WIDTH-30-10*2)/3.0;
        
        return 15+10*(colorm-1)+colorm*cellHeight+47;
        
    }else if (list.fieldType==8){
        
        
        return 80;
        
    }else if (list.fieldType==10)
    {
        
     
        return 60*SCREEN_WIDTH/320.0;
        
    }else{
        
        
        return 0;
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 30;
    
}


-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    RSData *Datamodel=self.ShopModel.data[section];
    
    RSTableHeadView *head=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    
    head.Rtitle=Datamodel.title;
    
    return head;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (indexPath.section<self.ShopModel.data.count-1) {
    
    RSData *Datamodel=self.ShopModel.data[indexPath.section];
    
    RSList *list=Datamodel.list[indexPath.row];
    
    if (list.fieldType==3) {
        
        if(!self.isOrder)
        {
            //躺框
            ChooseView *chooseView=[[ChooseView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kDevice_Is_iPhoneX?SCREEN_HEIGHT-64-IPhoneXTableHeight:SCREEN_HEIGHT-64) andDataArr:list.items andBlock:^(NSString *value, NSInteger index) {
                
                list.value=value;
                
                [self.RegisterTableView reloadData];
                
            }];
            
            [chooseView PopWithView:self.view];
        }
        
    }else if (list.fieldType==4)
    {
        
        
        //上传图片
        [self GotoLibaraySelectPhotoNum:1 andIsCantainScan:NO andBlock:^(NSString * armStr) {
            
            list.value=armStr;
            
            [self.RegisterTableView reloadData];
            
        }];
        
    }else if (list.fieldType==7)
    {
        //时间选择框
        
        NSDate *date;
        
        if (list.value.length==0) {
            
            date=[NSDate date];
            
        }else{
            
            date=[HelpWay stringToDateWithString:list.value];
            
            if (date==nil) {
                
                date=[NSDate date];
            }
            
        }
        
        DatePickView *datePick=[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kDevice_Is_iPhoneX?SCREEN_HEIGHT-64-IPhoneXTableHeight: SCREEN_HEIGHT-64) andDate:date andblock:^(NSDate *PickDate) {
            
            list.value=[HelpWay dateToStringWith:PickDate];
            
            [self.RegisterTableView reloadData];
            
        }];
        
        [datePick PopWithView:self.view];
        
    }else if (list.fieldType==9)
    {
        AcountGoodsViewController *AcountGoods=[AcountGoodsViewController new];
        
        [AcountGoods aspect_hookSelector:@selector(ChooseData:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspects,GoodListData*Sdata){
            
            [self addjustDataWithData:Sdata];
            
        } error:nil];
        
        [self.navigationController pushViewController:AcountGoods animated:YES];
        
    }
     }else{
         
         //单个台账点击事件,赋予值给第二组
         
         self.editAcount=YES;
         
         self.editRecoredRow=indexPath.row;
         
         NSDictionary *dict=self.postListArr[indexPath.row];
         
         RSData *Datamodel=self.ShopModel.data[1];
         
         for (RSList *list in Datamodel.list) {
         
             if ([list.fieldName isEqualToString:@"birthTime"]) {
              
                 list.value=[HelpWay timestampChangesStandarTime:dict[list.fieldName]];
                 
             }else if (![list.fieldName isEqualToString:@"btnSubmit"]) {
                 
                 if ([dict[list.fieldName] isKindOfClass:[NSNull class]]) {
                     
                     list.value=@"";
                 }else{
                 
                  list.value=[NSString stringWithFormat:@"%@",dict[list.fieldName]];
                     
                 }
             }
 
         }
         
         [self.RegisterTableView reloadData];

     }
    
}

-(void)ShowHEAD
{
    [self.ScanPhotoArr removeAllObjects];
    
    [self.ScanPhotoArr addObject:[MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",ReqUrl,self.headimage]]]];
    
    [self GoToPhotoScanAndIndex:0];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)textViewDidChange:(UITextView *)textView
{
    NSInteger tags=textView.tag;
    
    NSInteger section=(tags-8000)/1000;
    
    NSInteger row=(tags-8000)-section*1000;
    
    RSData *Datamodel=self.ShopModel.data[section];
    
    RSList *list=Datamodel.list[row];
    
    list.value=textView.text;
    
}

#pragma mark-重新刷新页面
- (void)actionTapEmptyDataSetNodataView
{
    [self loadDates];
    
}

-(void)GotoOption:(UIButton*)sender
{
   
    NSMutableDictionary *PostDIC=[NSMutableDictionary dictionary];
    
    //基本信息
    
    NSMutableDictionary *BaseDic=[NSMutableDictionary dictionary];
    
    RSData *Basedata=self.ShopModel.data[0];
    
    for (RSList *list in Basedata.list) {
        if (list.isVaild) {
            //必填的，如果没填，提示
            if (list.value==nil||list.value.length==0) {
                
                [MBProgressHUD showWarnMessage:[NSString stringWithFormat:@"%@不能为空",list.name]];
                
                return;
                
            }
            
            [BaseDic setValue:list.value forKey:list.fieldName];
            
        }else{
            //不必填的
            if (list.value==nil) {
                
                list.value=@"";
            }
            
            if (list.fieldName==nil) {
                
                list.fieldName=@"";
            }
            
          [BaseDic setValue:list.value forKey:list.fieldName];
            
        }
        
        
    }
    
    
    [PostDIC setValue:BaseDic forKey:@"baseInfo"];
    //数组信息

    [PostDIC setValue:self.postListArr forKey:@"details"];

    self.Reqmodel.postData=[HelpWay dictionaryToJSON:PostDIC];
    
     [self showLoadingAnimation];

    BaseReqApi *Api=[[BaseReqApi alloc]initWithRequestUrl:self.postUrl andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    [Api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
            
            [MBProgressHUD showSuccessMessage:self.OptionSussStr];
         
            _block();
                
            [self.navigationController popViewControllerAnimated:YES];
           
            
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }
        
    }];
    
}

#pragma mark-选择商品后

-(void)addjustDataWithData:(GoodListData*)Gdata
{
    
    
    RSData *data=self.ShopModel.data[1];

    for(RSList *list in data.list) {

        
        if ([list.fieldName isEqualToString:@"goodsName"]) {
            
            list.value=Gdata.goodsName;
        }else if ([list.fieldName isEqualToString:@"unit"])
        {
            list.value=Gdata.unit;
            
        }else if ([list.fieldName isEqualToString:@"goodsId"])
        {
            list.value=[NSString stringWithFormat:@"%ld",Gdata.goodsId];
            
        }else if ([list.fieldName isEqualToString:@"productSn"])
        {
            list.value=Gdata.productSn;
            
        }
        
    }
    
    [self.RegisterTableView reloadData];
    
}

-(void)addLocaCount
{
    //判断是否存在未填写的
    for (RSData*data in self.ShopModel.data) {
        
        for (RSList *list in data.list) {
        
            if (list.isVaild&&![list.fieldName isEqualToString:@"btnSubmit"]) {
                
                if (list.value==nil||list.value.length==0) {
                    
                    [MBProgressHUD showWarnMessage:[NSString stringWithFormat:@"%@不能为空",list.name]];
                    
                    return;
                    
                }
            }
 
        }
    }
    
    //如果全填写了
    
    if (self.editAcount) {
        //如果是编辑模式，先要删除数据线
        [self.postListArr removeObjectAtIndex:self.editRecoredRow];
        
        [self.AcountListArr removeObjectAtIndex:self.editRecoredRow];
 
    }
        RSData*data=self.ShopModel.data[1];
    
        NSMutableDictionary *ArmDict=[NSMutableDictionary dictionary];
    
        for (RSList *list in data.list) {

            if (![list.fieldName isEqualToString:@"btnSubmit"]) {
                
               [ArmDict setValue:list.value forKey:list.fieldName];
            }
            
            list.value=@"";//赋值后清空
            
        }
    
    [self.postListArr addObject:ArmDict];
    
    [self.AcountListArr addObject:[SAcountList mj_objectWithKeyValues:ArmDict]];

    [self.RegisterTableView reloadData];
    
    self.editAcount=NO;
    
    self.editRecoredRow=0;

    [self.RegisterTableView scrollToBottom];
    
}

#pragma ****************脚底视图********************
- (UIView*)Footview
{
    if(_Footview == nil)
    {
        _Footview = [[UIView alloc]init];
        
        if (kDevice_Is_iPhoneX) {
            
            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64-34, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }else{
            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }
        _Footview.backgroundColor = [UIColor whiteColor];
        
        UILabel *linelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        linelab.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        UILabel *totalMoneyLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
        totalMoneyLab.text = @"合计：0";
        totalMoneyLab.textColor = [UIColor redColor];
        totalMoneyLab.font = [UIFont systemFontOfSize:14];
        
        UILabel *totalCountLab = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetHeight(_Footview.frame)/2, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
        totalCountLab.text = @"品种数量：0";
        totalCountLab.textColor = [UIColor darkGrayColor];
        totalCountLab.font = [UIFont systemFontOfSize:14];
        
        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        nextBtn.backgroundColor = TBColorProvideBtnbg;
        nextBtn.enabled = YES;
        nextBtn.frame = CGRectMake(CGRectGetMaxX(totalMoneyLab.frame), 0, 90, CGRectGetHeight(_Footview.frame));
        [nextBtn setTitle:@"下单" forState:UIControlStateNormal];
        [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [nextBtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
        
        totalMoneyLab.text = [NSString stringWithFormat:@"合计：%.2f",self.moneyStr];
        totalCountLab.text = [NSString stringWithFormat:@"品种数量：%zd",self.countStr];
        
        [_Footview addSubview:linelab];
        [_Footview addSubview:self.totalMoneyLab = totalMoneyLab];
        [_Footview addSubview:self.totalCountLab = totalCountLab];
        [_Footview addSubview:nextBtn];
    }
    return _Footview;
}

#pragma mark-下单;
- (void)nextClick:(UIButton*)sender
{
    
    NSMutableDictionary *PostDIC=[NSMutableDictionary dictionary];
    
    //基本信息
    
    NSMutableDictionary *BaseDic=[NSMutableDictionary dictionary];
    
    RSData *Basedata=self.ShopModel.data[0];
    
    for (RSList *list in Basedata.list) {
        if (list.isVaild) {
            if(self.isOrder && [list.name isEqualToString:@"供应商"])
            {
                list.value = [NSString stringWithFormat:@"%zd",self.supplierId];
            }
            //必填的，如果没填，提示
            if (list.value==nil||list.value.length==0) {
        
                [MBProgressHUD showWarnMessage:[NSString stringWithFormat:@"%@不能为空",list.name]];
                
                return;
                
            }
            
            [BaseDic setValue:list.value forKey:list.fieldName];
            
        }else{
            //不必填的
            if (list.value==nil) {
                
                list.value=@"";
            }
            
            if (list.fieldName==nil) {
                
                list.fieldName=@"";
            }
            
            [BaseDic setValue:list.value forKey:list.fieldName];
            
        }
        
        
    }
    
    [PostDIC setValue:BaseDic forKey:@"baseInfo"];
    //数组信息
    
    NSMutableArray *detailArray = [NSMutableArray array];
    for(GoodListData *data in self.dataArray)
    {
        
        [detailArray addObject:data.mj_keyValues];
    }
    
    
    
    [PostDIC setValue:detailArray forKey:@"details"];
    
    
    
    self.Reqmodel.postData=[HelpWay dictionaryToJSON:PostDIC];
    
    
    
    [self showLoadingAnimation];
    
    BaseReqApi *Api=[[BaseReqApi alloc]initWithRequestUrl:self.postUrl andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:NO];
    
    [Api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        NSLog(@"%@",responseObject);
        
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
            
            [MBProgressHUD showSuccessMessage:self.OptionSussStr];
            
            _block();
        
            for(UIViewController *vv in self.navigationController.viewControllers)
            {
                if([vv isKindOfClass:[CandLViewController class]])
                {
                    [self.navigationController popToViewController:vv animated:YES];

                    return ;
                }else if ([vv isKindOfClass:[OutAccountViewController class]])
                {
                    [self.navigationController popToViewController:vv animated:YES];
                    
                    return ;
                }
            }
            
//            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }
        
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
